package com.wry.juc;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <h1>  </h1>
 *
 * @author wry
 * @since 2025.04.03
 */
public class CunCurrentLinked<E> {

    private E e;

    private final AtomicInteger size = new AtomicInteger(0);

    private CunCurrentLinked<E> head = null;

    private CunCurrentLinked<E> tail = null;

    private CunCurrentLinked<E> prev;

    private CunCurrentLinked<E> next;

    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public CunCurrentLinked() {
    }

    public CunCurrentLinked(E e) {
        this.e = e;
    }

    public void add(E e) {
        lock.writeLock().lock();
        CunCurrentLinked<E> newNode = new CunCurrentLinked<>(e);
        CunCurrentLinked<E> currentTail = tail;
        if (tail == null) {
            head = newNode;
            tail = newNode;
        } else {
            currentTail.next = newNode;
            newNode.prev = currentTail;
            tail = newNode;
        }
        size.incrementAndGet();
        lock.writeLock().unlock();
    }

    public E get(int index) {
        if (index >= size.get() || index < 0) {
            throw new IndexOutOfBoundsException("Index out of bounds: " + index);
        }
        lock.readLock().lock();
        int idx = 0;
        CunCurrentLinked<E> currentNode = head;
        while (idx < index) {
            currentNode = currentNode.next;
            idx++;
        }
        lock.readLock().unlock();
        return currentNode.e;
    }

    public static void main(String[] args) {
        CunCurrentLinked<String> linked = new CunCurrentLinked<>();
        linked.add("1");
        linked.add("2");
        linked.add("3");
        linked.add("4");

        System.out.println("链表大小->" + linked.size);
        for (int i = 0; i < linked.size.get(); i++) {
            System.out.println("元素->" + linked.get(i));
        }
        System.out.println("元素->" + linked.get(0));
    }
}
